<?php

include("config.php");
if (!isset($_SESSION["user"]) || $_SESSION["user"] == "") header('Location: index.php');


$db_www = new DB($server_username,$server_pass,$server_db,$server,$driver);
$db_rdata = new DB($rdata_server_username,$rdata_server_pass,$rdata_server_db,$rdata_server,$rdata_driver);
if ($db_www->isConnected()) {	
	$i_query = str_replace("<kodas>", $_SESSION['user'], $i_query);
	$minfo = $db_www->returnInfo($i_query);	
} else {
	die("Klientų aptarnavimo sistema laikinai neveikia.");
}
if (!$db_rdata->isConnected()) {	
	die("Klientų aptarnavimo sistema laikinai neveikia(rdata).");
}

	if (empty($minfo)) {
		die("Nerasta imone.");
	}

		if (isset($_REQUEST["from"])) {
			$from = convertdate($_REQUEST["from"],'iso','iso','.');
			if ($from == NULL) $from = firstOfPrevMonth();
		} else {
			$from = firstOfMonth();
		}
		if (isset($_REQUEST["to"])) {
			$to = convertdate($_REQUEST["to"],'iso','iso','.');
			if ($to == NULL) $to = lastOfPrevMonth();
		} else {
			$to = lastOfMonth();
		}	
		$k_query = str_replace("<kodas>", $minfo["N08_kodas_ks"], $k_query);
		$kinfo = $db_www->returnList($k_query);
		$numbers = "'333'";
		foreach ($kinfo as $card) {
			$numbers .= ",'" . trim($card["N51_PAV"]) . "'";
		}
		
		$sells_all_protocol = str_replace("<kodas>", $numbers, $sells_all_protocol);
		$sells_all_protocol = str_replace("<from>", str_replace(".","-",$from), $sells_all_protocol);
		$sells_all_protocol = str_replace("<to>", str_replace(".","-",$to), $sells_all_protocol);
		$info = $db_rdata->returnList($sells_all_protocol);


	$oinfo = $db_www->returnInfo($o_query);	
	if (!empty($oinfo)) {
		$o_query = str_replace("<kodas>", $oinfo["N23_REIKSME1"], $ii_query);
		$ourinfo = $db_www->returnInfo($o_query);	
		
		$s_query = str_replace("<kodas>", $oinfo["N23_REIKSME1"], $s_query);
		$saskinfo = $db_www->returnInfo($s_query);
	}

	$i_query = str_replace("<kodas>", $_SESSION['user'], $i_query);
	//echo $i_query;
	$minfo = $db_www->returnInfo($i_query);	

	$rinfo = $db_rdata->returnInfo("select * from n08_klij_c where N08_c_kodas_ks='" . $minfo["N08_kodas_ks"] . "'");



		$company = iconv('windows-1257', 'UTF-8', $ourinfo["N08_PAV"]);
		$address = iconv('windows-1257', 'UTF-8',$ourinfo["N08_ADR"]);
		
		$mcompany = iconv('windows-1257', 'UTF-8', $minfo["N08_PAV"]);
		$maddress = iconv('windows-1257', 'UTF-8',$minfo["N08_ADR"]);

		require_once('tcpdf/config/lang/eng.php');
		require_once('tcpdf/tcpdf.php');

		
// Extend the TCPDF class to create custom Header and Footer
class MYPDF extends TCPDF {

	private $hd = "header";
	
	public function setHeaderString($value){
		$this->hd = $value;
	}
	
    //Page header
    public function Header() {        
		$this->writeHTML($this->hd, true, false, true, false, '');
    }


}
			// get esternal file content


$header = "
<table cellspacing=\"0\" cellpadding=\"1\" border=\"0\">
    <tr>
        <td><font size=\"+1\">TIEKĖJAS (PARDAVĖJAS)</font>".
		"<br>".$company.
	    "<br>".$address.		
		"<br>
		<table cellspacing=\"0\" cellpadding=\"1\" border=\"0\" width=\"400\">
		<tr>
		<td width=\"150\">Įmonės kodas</td><td>".$ourinfo["N08_IM_KODAS"]."</td>
		</tr>
		<tr>
		<td>PVM kodas</td><td>".$ourinfo["N08_PVM_KODAS"]."</td>
		</tr>
		<tr>
		<td>Banko kodas</td><td>".iconv('windows-1257', 'UTF-8', $saskinfo["N33_KODAS_WS"] . " " . $saskinfo["N34_PAV"])."</td>
		</tr>
		<tr>
		<td>A.s.</td><td>".$saskinfo["N33_S_KODAS"]."</td>
		</tr>		
		</table><br><br>
		
		<font size=\"+1\">PIRKĖJAS (MOKĖTOJAS)</font>".
		"<br>".$mcompany.
	    "<br>".$maddress.	
		"<br>
		<table cellspacing=\"0\" cellpadding=\"1\" border=\"0\" width=\"400\">
		<tr>
		<td width=\"150\">Įmonės kodas</td><td>".$minfo["N08_IM_KODAS"]."</td>
		</tr>
		<tr>
		<td>PVM kodas</td><td>".$minfo["N08_PVM_KODAS"]."</td>
		</tr>
	
		</table>
		</td>
        <td align=\"right\"><img src=\"logo.jpg\" alt=\"test alt attribute\" height=\"100\" border=\"0\" /></td>
    </tr>
</table>	
<br>
<span style=\"text-align:center;\"><font size=\"+1\">PROTOKOLO ATASKAITA</font></span>	
<br><br>Periodas " . $from . "-" . $to;




	
		// create new PDF document
		$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);

		// set document information
		$pdf->SetCreator(PDF_CREATOR);
		$pdf->SetAuthor('Darius Mikėnas');
		$pdf->SetTitle('Kortelių ataskaita');
		$pdf->SetSubject('Ataskaita');
		$pdf->SetKeywords('Ataskaita');

		// set default header data
		$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
		$pdf->setHeaderString($header);
		$pdf->setPrintHeader(true);
		$pdf->setPrintFooter(false);

		// set default monospaced font
		$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

		//set margins
		$pdf->SetMargins(7, 80, 7);
		$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
		$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

		//set auto page breaks
		$pdf->SetAutoPageBreak(TRUE, 10);

		//set image scale factor
		$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);

		//set some language-dependent strings
		$pdf->setLanguageArray($l);

		// ---------------------------------------------------------

		// set font
		$pdf->SetFont('freesans', '', 8);
		$pdf->setHeaderFont(Array('freesans', '', 8));

		$pdf->setJPEGQuality(75);
		
		// add a page
		$pdf->AddPage();




$viso = 0;
$visobepvm = 0;
$visobepvm1 = 0;
$visobepvm2 = 0;
$visoviso = 0;
$visonuol = 0;
$visovisokiekis = 0;
$visovisonuol = 0;
$visol = 0;
$data = "";
$prev_card = "";
$html = "";


	foreach ($info as $card) {
		$p_query = str_replace("<barkodas>", $card["Barkodas"] , $prek_query);
		$pinfo = $db_www->returnInfo($p_query);
		if (!empty($pinfo)) $pav = iconv('windows-1257', 'UTF-8',trim($pinfo["n37_pav"]));
		else $pav = "";
		if (!empty($pinfo)) $vnt = iconv('windows-1257', 'UTF-8',trim($pinfo["n37_kodas_us"]));
		else $vnt = "";		
		
		if ($card["arprotokolo"]==1) {
			if (!empty($rinfo)) {
				if ($rinfo['n08_c_protokolas_n']==null || $rinfo['n08_c_protokolas_n']==0) {
					$antk = sprintf("%01.3f",$rinfo['n08_c_protokolas']);
				} else {
					$sql = "select n.N07_KODAS_LS_6 from i24_rys i,n07_imon n where i.I24_KODAS_KK='".$card["AparatoID"]."' and n.N07_KODAS_Is=i.I24_KODAS_IS";
					$dinfo = $db_www->returnInfo($sql );
					if (!empty($dinfo) && trim($dinfo['N07_KODAS_LS_6'])=='NPARTNERIS') {
						$antk = sprintf("%01.3f",$rinfo['n08_c_protokolas_n']);
					} else {
						$antk = sprintf("%01.3f",$rinfo['n08_c_protokolas']);
					}
				} 
			} else {
				$antk = 0;
			} 
			//echo $card["X02_kaina"];
			if ($card["Kiekis"] != null && $card["Kiekis"] != 0  && $card["X02_kaina"]!= null) {
				$pvm = $card["Mokesciai"]/($card["Suma"]-$card["nuolaida"])*100;
				$antkpvm = $antk/100*$pvm;
				$suma = sprintf("%01.4f",(($card["X02_kaina"]+$antk)-(($card["X02_kaina"]+$antk)/100*$pvm)));
				$sumabepvm =  sprintf("%01.3f",($card["X02_kaina"]+$antk));
				//echo $sumabepvm;
				$visobepvm =  sprintf("%01.4f",($suma*$card["Kiekis"]));
				$s = sprintf("%01.2f",($sumabepvm*$card["Kiekis"]));
			} else {
				$suma = "0";
				$visobepvm = "0";
				$sumabepvm = "0";
				$s = "0";
			}		
			
			
		} else {
			$antk = '0';
			if ($card["Kiekis"] != null && $card["Kiekis"] != 0) {
				$suma = sprintf("%01.4f",($card["Suma"]-$card["Mokesciai"])/$card["Kiekis"]);
				$visobepvm = sprintf("%01.4f",($card["Suma"]-$card["Mokesciai"]));
				$sumabepvm = sprintf("%01.2f",$card["Suma"]/$card["Kiekis"]);
			} else {
				$suma = "0";
				$visobepvm = "0";
				$sumabepvm = "0";
			}
			$s = sprintf("%01.2f",$card["Suma"]);
		}
		$sbnl = $card["Suma"]+$card["nuolaida"];
		
		$antk = trim(sprintf("%01.3f",$card["Suma"]-$s));
		//echo $antk;
		$nr = trim($card["KortelesNr"]);
		$card_q = str_replace("<im_kodas>", $minfo["N08_kodas_ks"], $card_query_nr);
		$card_q = str_replace("<kodas>", $nr , $card_q);
		$cinfo = $db_www->returnInfo($card_q);
		
		//echo $prev_card . " " . $nr . " " . ($nr === $prev_card) ."<br>";
		if ($nr === $prev_card) {
		} else {
			if ($prev_card != "") {
				$html .= "<tr><td colspan=\"5\"><font size=\"-2\">Viso kortelei</font></td><td><font size=\"-2\">";
				if ($visol!='0' && $visol!='0.00'){
				  $html .= sprintf("%01.2f",$visol);
				} 
				$html .= "</font></td><td colspan=\"2\"></td><td colspan=\"3\"><font size=\"-2\">";
				if ($visonuol!='0' && $visonuol!='0.00'){
					$html .= sprintf("%01.2f",$visonuol);
				}
				$html .= "</font></td><td><font size=\"-2\">";
				if ($visobepvm1!='0' && $visobepvm1!='0.00'){
				  $html .= sprintf("%01.2f",$visobepvm1);
				} 
				$html .= "</font></td><td><font size=\"-2\">";
				if ($viso!='0' && $viso!='0.00'){
				  $html .= sprintf("%01.2f",$viso);
				} 				
				$html .= "</font></td></tr>";
				$html .= "</table><br><br>";
				$visoviso += $viso;
				$visobepvm2 += $visobepvm1;
				$visovisonuol += $visonuol;	
				$visovisokiekis += $visol;
				$viso = 0;				
				$visobepvm1 = 0;
				$visol = 0;	
				$visonuol = 0;				
			}
			if (!empty($cinfo)) $pastabos = iconv('windows-1257','UTF-8',trim($cinfo["N51_KORTA"]));
			else $pastabos = "";
			$html .= "<table cellspacing=\"0\" cellpadding=\"1\" border = \"0\">
				<tr style=\"background-color:#EFF9E5;\"><th colspan=\"10\">Kortelė : " . $nr . "    " . $pastabos . "</th></tr>		
				<tr style=\"background-color:#EFF9E5;\"><th style=\"width:75px;\"><font size=\"-2\">Data, laikas</font></th><th style=\"width:90px;\"><font size=\"-2\">Vieta</font></th><th style=\"width:45px;\"><font size=\"-2\">Kvito nr.</font></th><th style=\"width:60px;\"><font size=\"-2\">Barkodas</font></th><th style=\"width:92px;\"><font size=\"-2\" >Prekės pavadinimas</font></th><th style=\"width:45px;\"><font size=\"-2\">Kiekis</font></th><th  style=\"width:23px;\"><font size=\"-2\">Mato<br>vnt.</font></th><th  style=\"width:40px;\"><font size=\"-2\">Pardavimo suma be<br>nuolaidos</font></th><th  style=\"width:35px;\"><font size=\"-2\">Nuol.<br>suma</font></th><th  style=\"width:44px;\"><font size=\"-2\">Vnt. kaina be PVM</font></th><th  style=\"width:45px;\"><font size=\"-2\">Vnt. kaina su PVM</font></th><th  style=\"width:50px;\"><font size=\"-2\">Suma viso be PVM</font></th><th style=\"width:50px;\"><font size=\"-2\">Suma viso</font></th></tr>
			";
			$prev_card = $nr;			
		}
		


		
		$html .= "<tr>";
		$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-2\">".$card["Year"] . "-" . sprintf('%02d',$card["Month"]) . "-" . sprintf('%02d',$card["Day"]) . " " . sprintf('%02d',$card["Hour"]) . ":" . sprintf('%02d',$card["Minute"])."</font></td>";
		$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-2\">".trim(@iconv('windows-1257','UTF-8',$card["AparatoPavadinimas"]))."</font></td>";
		$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-2\">".trim($card["KvitoNr2"])."</font></td>";
		$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-2\">".trim($card["Barkodas"])."</font></td>";
		$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-2\">".htmlspecialchars($pav)."</font></td>";
		$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-2\">".trim(sprintf("%01.2f",$card["Kiekis"]))."</font></td>";
		$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-2\">".$vnt."</font></td>";
		$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-2\">";
		if ($sbnl!='0' && $sbnl!='0.00'){
			$html .= sprintf("%01.2f",$sbnl);
		}

		$html .= "</font></td>";
		$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-2\">";
		if ($antk!='0' && $antk!='0.00' && $antk!='0.000'){
			$html .= sprintf("%01.3f",$antk);
		}
		
		$html .= "</font></td>";
		
		$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-2\">";
		if ($suma!='0' && $suma!='0.00' && $suma!='0.000'){
			$html .= sprintf("%01.3f",$suma);
		}
		$html .="</font></td>";
		$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-2\">";
		if ($sumabepvm!='0' && $sumabepvm!='0.00'){
			$html .= sprintf("%01.3f",$sumabepvm);
		}
		$html .="</font></td>";
		$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-2\">";
		if ($visobepvm!='0' && $visobepvm!='0.00'){
			$html .= sprintf("%01.2f",$visobepvm);
		}
		$html .= "</font></td>";
		$html .= "<td style=\"border-bottom:1px solid #EFF9E5;\"><font size=\"-2\">";
		if ($s!='0' && $s!='0.00'){
			$html .= sprintf("%01.2f",$s);
		}
		$html .="</font></td>";
		$html .= "</tr>";
		
		
		
		$visol += $card["Kiekis"];
		$viso += $s;
		$visobepvm1 += $visobepvm;
		$visonuol += $antk;

	}
	if ($viso > 0) {
		$html .= "<tr><td colspan=\"5\"><font size=\"-2\">Viso kortelei</font></td><td><font size=\"-2\">";
		if ($visol!='0' && $visol!='0.00'){
		  $html .= sprintf("%01.2f",$visol);
		}
		$html .= "</font></td><td colspan=\"2\"></td><td colspan=\"3\"><font size=\"-2\">".sprintf("%01.3f",$visonuol)."</font></td><td><font size=\"-2\">";
		if ($visobepvm1!='0' && $visobepvm1!='0.00'){
		  $html .= sprintf("%01.2f",$visobepvm1);
		}
		$html .= "</font></td><td><font size=\"-2\">";
		if ($viso!='0' && $viso!='0.00'){
		  $html .= sprintf("%01.2f",$viso);
		}
		$html .= "</font></td></tr>";
		$visoviso += $viso;	
		$visovisonuol += $visonuol;	
		$visovisokiekis += $visol;
		$visobepvm2 += $visobepvm1;
	}
	if ($viso > 0) {
		$html .= "<tr><td colspan=\"10\"></td></tr>";
		$html .= "<tr style=\"background-color:#EFF9E5;\"><td colspan=\"4\"><font size=\"-2\">Viso organizacijai</font></td><td></td><td colspan=\"3\"><font size=\"-2\">";
		if ($visovisokiekis!='0' && $visovisokiekis!='0.00'){
		  $html .= sprintf("%01.2f",$visovisokiekis);
		}
		$html .= "</font></td><td colspan=\"3\"><font size=\"-2\">".sprintf("%01.3f",$visovisonuol)."</font></td><td><font size=\"-2\">";
		if ($visobepvm2!='0' && $visobepvm2!='0.00'){
		  $html .= sprintf("%01.2f",$visobepvm2);
		}		
		$html .= "</font></td><td><font size=\"-2\">";
		if ($visoviso!='0' && $visoviso!='0.00'){
		  $html .= sprintf("%01.2f",$visoviso);
		}			
		$html .= "</font></td></tr>";
		$html .= "</table><br><br>";
	}

$pdf->writeHTML($html, true, false, true, false, '');

	
		
		// ---------------------------------------------------------



		//Close and output PDF document
		$pdf->Output('protokolo_ataskaita.pdf', 'D');

?>